package com.uchedao.vehicledetection.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.global.GlobalInfo;
import com.uchedao.vehicledetection.model.ResultIntArrayPics;
import com.uchedao.vehicledetection.utils.Util;
import com.uchedao.vehicledetection.view.widget.BadgeView;
import com.uchedao.vehicledetection.view.widget.stickylistheaders.StickyListHeadersAdapter;

import java.util.ArrayList;

public class GuiseAdapter extends BaseAdapter implements
        StickyListHeadersAdapter {

    private Context mContext;
    private ResultIntArrayPics[] arrays;
    private LayoutInflater inflater;
    private GuiseAdapterListener listener;
    private String[] values;
    private boolean[] checkedItems;
    private int index;

    public interface GuiseAdapterListener {
        /**
         * 图片添加
         *
         * @param result
         */
        public void onPhotoAdd(ResultIntArrayPics result);

        /**
         * 图片修改
         *
         * @param result
         */
        public void onPhotoEdit(ResultIntArrayPics result);
    }

    public GuiseAdapter(Context act, ResultIntArrayPics[] arrays,
                        GuiseAdapterListener skeletonAdapterListener) {
        inflater = LayoutInflater.from(act);
        this.arrays = arrays;
        mContext = act;
        listener = skeletonAdapterListener;
        values = GlobalInfo.resources
                .getStringArray(R.array.guise_select_values);
    }

    public GuiseAdapter(Context act, ResultIntArrayPics[] arrays,
                        GuiseAdapterListener skeletonAdapterListener, String[] values) {
        inflater = LayoutInflater.from(act);
        this.arrays = arrays;
        mContext = act;
        listener = skeletonAdapterListener;
        this.values = values;
    }

    @Override
    public int getCount() {
        return arrays.length;
    }

    @Override
    public Object getItem(int position) {
        return arrays[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    class ViewHolder {
        TextView titleTv;
        TextView valueTv;
        LinearLayout photoContainer;
        View gapView;
        FrameLayout photoFl;
        ImageView photoIv;
        BadgeView badge;
        ImageView photoAddIv;
    }

    private OnClickListener photoAddListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (listener != null)
                listener.onPhotoAdd((ResultIntArrayPics) v.getTag());

        }
    };

    private OnClickListener resultListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            index = (Integer) v.getTag();
            showAlertMultipleChoiceDialog(arrays[index], multipleChoiceListener);
        }
    };

    /**
     * 多选监听
     */
    private DialogInterface.OnMultiChoiceClickListener multipleChoiceListener = new DialogInterface.OnMultiChoiceClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {

            ListView listView = ((AlertDialog) dialog).getListView();

            // 取消选择
            if (!isChecked) {
                // 当选中的数量小于1时
                if (listView.getCheckedItemCount() == 0) {
                    listView.setItemChecked(which, true);
                    checkedItems[which] = true;
                    Toast.makeText(mContext, R.string.at_least_choice_one,
                            Toast.LENGTH_LONG).show();
                }
                return;

            }

            // 若该选项只能单选
            if (multipleValueOnlyRadio(values[which])) {
                // 除此项外，其余值取消选择
                for (int i = 0; i < values.length; i++) {
                    listView.setItemChecked(i, i == which);
                    checkedItems[i] = (i == which);
                }

                // 若该选项能多选
            } else {

                for (int i = 0; i < values.length; i++) {
                    // 其余单选项取消选择
                    if (multipleValueOnlyRadio(values[i])) {
                        listView.setItemChecked(i, false);
                        checkedItems[i] = false;
                    }
                }
            }
        }
    };

    /**
     * 显示多选对话框
     *
     * @param item
     * @param listener
     */
    private void showAlertMultipleChoiceDialog(ResultIntArrayPics item,
                                               DialogInterface.OnMultiChoiceClickListener listener) {
        ArrayList<Integer> ints = item.result;
        checkedItems = new boolean[values.length];
        for (int i : ints)
            checkedItems[i] = true;

        DialogInterface.OnClickListener okClickListener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                ResultIntArrayPics item = arrays[index];

                ArrayList<Integer> ints = new ArrayList<Integer>();
                for (int i = 0; i < checkedItems.length; i++) {
                    if (checkedItems[i])
                        ints.add(i);
                }
                item.result = ints;
                notifyDataSetChanged();

            }
        };
        new AlertDialog.Builder(mContext).setTitle(item.name)
                .setMultiChoiceItems(values, checkedItems, listener)
                .setPositiveButton(R.string.ok, okClickListener)
                .setNegativeButton(R.string.cancel, null).create().show();

    }

    private OnClickListener editPicListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (listener != null)
                listener.onPhotoEdit((ResultIntArrayPics) v.getTag());
        }

    };

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.item_accident_skeleton,
                    null);
            convertView.setTag(viewHolder);
            viewHolder.titleTv = (TextView) convertView
                    .findViewById(R.id.skeleton_item_title_tv);
            viewHolder.valueTv = (TextView) convertView
                    .findViewById(R.id.skeleton_item_result_tv);
            viewHolder.photoContainer = (LinearLayout) convertView
                    .findViewById(R.id.skeleton_item_photo_container);
            viewHolder.photoFl = (FrameLayout) convertView
                    .findViewById(R.id.skeleton_item_photo_fl);
            viewHolder.photoIv = (ImageView) convertView
                    .findViewById(R.id.skeleton_item_photo_iv);
            viewHolder.badge = new BadgeView(mContext);
            viewHolder.badge.setBackground(9,
                    GlobalInfo.resources.getColor(R.color.deep_red));
            viewHolder.badge.setTargetView(viewHolder.photoFl);

            viewHolder.badge.setBadgeMargin(4);
            viewHolder.photoAddIv = (ImageView) convertView
                    .findViewById(R.id.skeleton_item_add_photo_iv);
            // viewHolder.valueTv.setMinWidth(resultTvWidth);
            viewHolder.valueTv.setOnClickListener(resultListener);
            viewHolder.photoAddIv.setOnClickListener(photoAddListener);
            viewHolder.photoIv.setOnClickListener(editPicListener);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        ResultIntArrayPics item = arrays[position];
        viewHolder.photoAddIv.setTag(item);
        viewHolder.photoIv.setTag(item);

        boolean addIvVisible = !setResult(item, viewHolder.valueTv);
        viewHolder.photoAddIv.setVisibility(addIvVisible ? View.VISIBLE
                : View.INVISIBLE);
        if (item.pic_path_list.size() > 0) {
            viewHolder.photoFl.setVisibility(View.VISIBLE);
            Bitmap bitmap = Util.getimage(item.pic_path_list.get(0), 300, 300);
            if (bitmap == null)
                viewHolder.photoIv
                        .setImageResource(R.mipmap.ic_launcher);
            else
                viewHolder.photoIv.setImageBitmap(bitmap);
        } else {
            viewHolder.photoFl.setVisibility(View.GONE);
        }
        viewHolder.badge.setBadgeCount(item.pic_path_list.size());

        viewHolder.titleTv.setText(item.name);
        viewHolder.valueTv.setTag(position);

        return convertView;
    }

    /**
     * 只能单选的多选值
     *
     * @param value
     * @return
     */
    private boolean multipleValueOnlyRadio(String value) {
        return "正常".equals(value) || "无".equals(value) || "丢失".equals(value);
    }

    /**
     * 是否正常结果
     *
     * @param value
     * @return
     */
    private boolean isRegularResult(String value) {
        return "正常".equals(value) || "无".equals(value);
    }

    /**
     * 设置值
     *
     * @param item
     * @param tv
     */
    private boolean setResult(ResultIntArrayPics item, TextView tv) {

        // 若为空值，默认为0
        if (item.result.size() == 0)
            item.result.add(0);

        String value = "";
        for (int i : item.result) {
            if (TextUtils.isEmpty(value))
                value = values[i];
            else
                value += " " + values[i];
        }
        tv.setText(value);

        if (isRegularResult(values[item.result.get(0)])) {// 正常
            tv.setBackgroundResource(R.color.deep_green);
            tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_blue_yes,
                    0, R.mipmap.ic_drop_arrow, 0);
            return true;
        } else {
            tv.setBackgroundResource(R.color.deep_red);
            tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_red_cross,
                    0, R.mipmap.ic_drop_arrow, 0);
            return false;
        }

    }

    class HeaderViewHolder {
        // TextView imageTv;
//        ImageView showDetail;
        TextView title;
    }

    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        HeaderViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new HeaderViewHolder();
            convertView = inflater.inflate(R.layout.item_accident_skeleton_subject,
                    null);
            convertView.setTag(viewHolder);
            viewHolder.title = (TextView) convertView
                    .findViewById(R.id.skeleton_subject_name_tv);
//            viewHolder.showDetail = (ImageView) convertView
//                    .findViewById(R.id.skeleton_subject_show_iv);
//            viewHolder.showDetail.setVisibility(View.INVISIBLE);

        } else {
            viewHolder = (HeaderViewHolder) convertView.getTag();
        }
        ResultIntArrayPics item = arrays[position];
        viewHolder.title.setText(item.header);
//        viewHolder.showDetail.setTag(item.header);

        return convertView;
    }

    @Override
    public long getHeaderId(int position) {
        return arrays[position].header.hashCode();
    }
}
